function timestampToTime(timestamp) {
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        return Y+M+D+h+m+s;
    }




//字符串转时间
function timeStringToTime(timeString){

	date = timeString.substring(0,19);    
	date = date.replace(/-/g,'/'); 
	timestamp = new Date(date).getTime();
	return timestamp;
}


//s计算时间差
function  timeDifference(faultDate,completeTime){
	
	var stime = new Date(faultDate*1000);
	var etime =new Date(completeTime*1000);
	var usedTime = etime - stime;  //两个时间戳相差的毫秒数

	var days=Math.floor(usedTime/(24*3600*1000))

	var leave1=usedTime%(24*3600*1000);    //计算天数后剩余的毫秒数
	var hours=Math.floor(leave1/(3600*1000));
	
	var leave2=leave1%(3600*1000);        //计算小时数后剩余的毫秒数
	var minutes=Math.floor(leave2/(60*1000));
	
	var leave3=leave2%(60*1000)      //计算分钟数后剩余的毫秒数
	var seconds=Math.round(leave3/1000)
	
	return days+"天"+hours +"小时"+minutes+"分钟"+seconds+"秒";
}

layui.use(['form','layer','table','laytpl','laydate','element'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        element=layui.element,
        laytpl = layui.laytpl,
        table = layui.table,
    	laydate = layui.laydate;

    laydate.render({
        elem: '#start',
        type: 'datetime'
    });
    laydate.render({
        elem: '#stop',
        type: 'datetime'
    });

    var tableVue=new Vue({
        el: '#carouselList',
        data:{
            all_data:null,
            tableIns:null,
            tableIndex:0,
            tableSwitch:true
        },
        methods:{
            tablefill:function(){
                this.tableIns =table.render({
                    cellMinWidth : 95,
                    page : true,
                    height : "full-125",
                    elem: '#carouselList',
                    id : "carouselListTable",
                    cols: [[ //标题栏

                        {field: 'id', title: 'id', minWidth:20,width:50, align:"center"},
                        {field: 'novel', title: '书名', minWidth:100,align:"center", templet:function(d){

                                return d.novel==null?'不存在':d.novel.novelName
                            }},
                        {field: 'novel', title: '作者', minWidth:80,align:"center",templet:function(d){
							
								
                          	return d.novel==null||d.novel.author==null?'不存在':d.novel.author.penName
                        }},
                        {field: 'startTime', title: '开始时间', minWidth:100, align:"center",templet:function(d){
                                return d.startTime!='0'?timestampToTime(d.startTime):'无效时间'
                         }},
                        {field: 'stopTime', title: '结束', align:'center',minWidth:50,templet:function(d){
                                return d.startTime!='0'?timestampToTime(d.stopTime):'无效时间'
                            }},
                        { title: '时长', align:'center',minWidth:50,templet:function(d){
                        		
                                return timeDifference(d.startTime,d.stopTime)
                         }},

                        {title: '操作', minWidth:170, templet:'#authorListBar',fixed:"right",align:"center"}
                    ]],data:this.all_data

                });
            },
            //查询今天正在显示轮播图
            getNowDaysData:function () {
				var url=global_url+'/admin/carousel/now'
				
				this.$http.get(url)
					.then(
					response=>{
						this.all_data=response.body.datas
						this.tablefill()
					},					
					response=>{
				})
           },
            //查询今日的轮播图
            getDaysData:function(){
        		var url=global_url+'/admin/carousel/nowadays'
		
				this.$http.get(url)
					.then(
					response=>{
						this.all_data=response.body.datas
						this.tablefill()
					},					
					response=>{
				})
           },
           //查询今日过期的轮播图
           getDaysDataInvalid:function(){
           		var url=global_url+'/admin/carousel/nowaday/invalid'
				
				this.$http.get(url)
					.then(
					response=>{
						this.all_data=response.body.datas
						this.tablefill()
					},					
					response=>{
				})
          },
          //删除
          deleteCarousel:function(id,obj){
      		
      		var url=global_url+'/admin/carousel/delete';
          	data={
          		"id":id
          	};
      		this.$http.post(url,data)
				.then(
				response=>{
					layer.msg(response.body.datas)
					obj.del();
					updataTableFill(tableVue.tableIndex);
					
				},					
				response=>{
			});
          	
         },
         //搜索
         searchCarousel:function(startTime,stopTime){
      		var url=global_url+'/admin/carousel/date?starDate='+timeStringToTime(startTime)+"&stopDate="+timeStringToTime(stopTime);

			this.$http.get(url)
				.then(
				response=>{
					tableVue.tableSwitch=false;
	         		element.tabChange('demo', 'search');
	         		this.all_data=response.body.datas
					this.tablefill()
					tableVue.tableSwitch=true;
				},					
				response=>{
			});
         		
         }
        }
    });


	tableVue.getNowDaysData()


    //一些事件监听
    element.on('tab(demo)', function(data){
    
    	if(data.index==3&&tableVue.tableSwitch){
    		layer.msg("请搜索");
    		element.tabChange('demo', 'index');
    	}
    	
    	tableVue.tableIndex=data.index;
    	
        updataTableFill(tableVue.tableIndex);
        
        
    });
    
    
    function updataTableFill(index){
    	//当前展示
        if(index==0){
        	tableVue.getNowDaysData()
        }
        
        //今日
        else if(index==1){
        	tableVue.getDaysData()
        }
        
        //今日过期
        else if(index==2){
        	tableVue.getDaysDataInvalid()
        }
    }




    //添加用户
    function addCarousel(edit){
        var index = layui.layer.open({
            title : "添加轮播",
            type : 2,
            content : "carouselInfo.html",
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                
               	if(edit){
               	   console.log(edit)
                   body.find(".id").val(edit.id);  //id
                   body.find(".novel_id").val(edit.nid);  //小说id
                   body.find(".img").val(edit.image);    //宽图
                   body.find(".start").val(timestampToTime(edit.startTime));    //开始日期
                   body.find(".stop").val(timestampToTime(edit.stopTime))  //结束日期
              
               	}
            
               	form.render();

                setTimeout(function(){
                    layui.layer.tips('点击此处返回轮播列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(window.sessionStorage.getItem("index"));
        })


    }




    $(".normal_btn").click(function(){
        addCarousel();
    })


    $(".search_btn").click(function () {
        start=$("#start").val()
        stop=$("#stop").val()
        if (start == "" || stop == "") {
            layer.msg("时间不能为空");
            return
        }
        
	
		tableVue.searchCarousel(start,stop)
		
		
    })
    
    
    
    
    
      //列表操作
    table.on('tool(carouselList)', function(obj){
        var layEvent = obj.event,
        data = obj.data;

		if(layEvent=='delte'){
		
			tableVue.deleteCarousel(data.id,obj)
		}else{
			addCarousel(data)
		}
				
    });
    
    
    





})
